//! 利润清算模块
//!
//! 用于处理用户的行为合法判断, 利润结算, 包括计算未实现利润和已实现利润,手续费等数据,
//! 提供清算报表, 利润对账单等功能
use super::CONFIG;
use crate::engine::{MatchEngineTrait, Trade};
use anyhow::Result;
use core::panic;
use dashmap::{DashMap, DashSet};
use eztrade_dto::{
    events::{self, SubscribeEvent},
    order::{Direction, Order, OrderStatus, PositionEffect},
    user::{Portfolio, Position}, Message,
};
use rayon::prelude::*;
use std::{
    collections::VecDeque,
    sync::{
        Arc, RwLock,
        atomic::{AtomicU64, Ordering},
    },
};

/// 客户端交易记录和当前记录, 用于快速索引以及转为可序列化的Portfolio
#[derive(Debug)]
pub struct ClientRecord {
    pub client_id: u64, // 用户ID(哈希, 可通过该标识重新连接)
    pub positions_map: DashMap<(String, Direction), Position>, // 品种/方向 -> 持仓
    pub balance_cent: i64, // 账户余额(单位: 分)
    pub balance_available: i64, // 可用余额(单位: 分)
    pub pending_orders: DashMap<u64, Arc<RwLock<Order>>>, // 待处理订单集合
    pub active_orders: DashMap<u64, Arc<RwLock<Order>>>, // 激活中的订单(订单簿)
    pub canceled_orders: VecDeque<Order>, // 已撤销订单集合
    pub done_orders: VecDeque<Order>, // 已完成订单集合
    pub done_subscribe: Option<Arc<SubscribeEvent>>, // 订阅的事件(仅订单完成)
}

impl ClientRecord {
    pub fn new(client_id: u64) -> Self {
        if client_id == 0 {
            return Self {
                client_id,
                positions_map: DashMap::new(),
                balance_cent: 0, // Maker默认0
                balance_available: 0,
                pending_orders: DashMap::new(),
                active_orders: DashMap::new(),
                canceled_orders: VecDeque::new(),
                done_orders: VecDeque::new(),
                done_subscribe: None,
            };
        };
        Self {
            client_id,
            positions_map: DashMap::new(),
            balance_cent: CONFIG.initial_balance_cent,
            balance_available: CONFIG.initial_balance_cent,
            pending_orders: DashMap::new(),
            active_orders: DashMap::new(),
            canceled_orders: VecDeque::new(),
            done_orders: VecDeque::new(),
            done_subscribe: None,
        }
    }

    pub fn to_portfolio(&self) -> Portfolio {
        let positions_vec: Vec<Position> = self
            .positions_map
            .par_iter()
            .map(|entry| {
                let (symbol, side) = entry.key();
                let position = entry.value();
                Position {
                    symbol: symbol.clone(),
                    side: *side,
                    cost: position.cost,
                    quantity: position.quantity,
                    liquidatable: position.liquidatable,
                }
            })
            .collect();
        Portfolio {
            client_id: self.client_id,
            positions: positions_vec,
            balance_cent: self.balance_cent,
            balance_available: self.balance_available,
        }
    }

    #[tracing::instrument(skip(self, order), fields(client_id = self.client_id, order_id = order.id))]
    pub fn insert_done_order(&mut self, order: Order) {
        // 此处处理所有持仓和冻结余额变动
        let order_id = order.id.expect("订单ID不能为空");
        let mut price_per_s = match order.frozen_price {
            Some(price) => price as i64,
            None => {
                log::error!("user_id {}, 订单{:?} 冻结价格为空", self.client_id, order);
                panic!("冻结价格为空不合理");
            }
        };
        // 如果存在订阅则发送事件
        if let Some(event) = &self.done_subscribe {
            let sender = event.get_sender();
            let _ = sender.send(Message::Order(order.clone()));
        }
        match order.status {
            OrderStatus::Canceled | OrderStatus::Rejected => {
                // 返回冻结余额或者持仓
                let key = (order.symbol.clone(), order.direction);
                match order.position_effect {
                    PositionEffect::Open => {
                        let available_back = match price_per_s.checked_mul(order.quantity as i64) {
                            Some(value) => value,
                            None => {
                                log::error!(
                                    "user_id {} 计算可用余额时溢出, Price: {}, Quantity: {}",
                                    self.client_id,
                                    price_per_s,
                                    order.quantity
                                );
                                panic!("计算可用余额时溢出");
                            }
                        };
                        self.balance_available += available_back; // 加上可用余额
                        if self.balance_available > self.balance_cent {
                            log::error!(
                                "user_id {} 账户余额不齐{}>{}",
                                self.client_id,
                                self.balance_available,
                                self.balance_cent
                            );
                            panic!("补回冻结余额后大于实际可用余额");
                        }
                    }
                    PositionEffect::Close => {
                        if let Some(mut position) = self.positions_map.get_mut(&key) {
                            position.liquidatable += order.quantity;
                            if position.liquidatable > order.quantity {
                                log::error!(
                                    "user_id {} position {:?}",
                                    self.client_id,
                                    position.clone()
                                );
                                panic!("补回冻结数量大于实际持仓数量!");
                            }
                        }
                    }
                }
                self.canceled_orders.push_back(order);
            }
            OrderStatus::Filled => {
                // 根据订单情况更新Portfolio
                let symbol = order.symbol.clone();
                let direction = order.direction;
                let key = (symbol.clone(), direction);
                let price = order.price.unwrap();
                if let Some(mut position) = self.positions_map.get_mut(&key) {
                    match order.position_effect {
                        PositionEffect::Open => {
                            // 开仓时更新成本和数量
                            position.cost = (position.cost * position.quantity as f64
                                + price * order.quantity as f64)
                                / (position.quantity + order.quantity) as f64; // 平均成本
                            position.quantity += order.quantity;
                            position.liquidatable += order.quantity;
                        }
                        PositionEffect::Close => {
                            // 平仓时减少数量
                            position.quantity -= order.quantity;
                            // 冻结资金添加回去
                            if order.direction == Direction::Long {
                                // 多单平仓, 资金+利润
                                self.balance_available = std::cmp::min(
                                    self.balance_available + order.quantity as i64 * price_per_s,
                                    self.balance_cent,
                                );
                            } else {
                                // 空单平仓, 资金+保证金+利润(卖价-买价)
                                price_per_s = (2.0 * position.cost
                                    - order.price.unwrap_or(0.0) * 100.0)
                                    as i64;
                                self.balance_available = std::cmp::min(
                                    self.balance_available + order.quantity as i64 * price_per_s,
                                    self.balance_cent,
                                );
                            }
                            // 流动性部分在校验时已经减去了
                            // position.liquidatable -= order.quantity;
                        }
                    }
                    tracing::debug!("ID:{} 更新仓位: {:?}", self.client_id, position.clone());
                } else {
                    let position = Position {
                        symbol: symbol,
                        side: direction,
                        cost: price,
                        quantity: order.quantity,
                        liquidatable: order.quantity,
                    };
                    tracing::debug!("ID:{} 新建仓位: {:?}", self.client_id, position);
                    self.positions_map.insert(key, position);
                }
                self.done_orders.push_back(order);
            }
            _ => {
                log::error!("该状态订单不该被处置进账户完结单内: {:?}", order);
            }
        }
        // 从active_orders中移除
        self.active_orders.remove(&order_id);
    }

    pub fn query_order(&self, order_id: u64) -> Option<Order> {
        // 查询待处理订单
        if let Some(arc_order) = self.pending_orders.get(&order_id) {
            let order = arc_order.read().unwrap();
            return Some(order.clone());
        }
        // 查询活跃订单
        if let Some(arc_order) = self.active_orders.get(&order_id) {
            let order = arc_order.read().unwrap();
            return Some(order.clone());
        }
        // 查询已完结订单
        for order in &self.done_orders {
            if order.id == Some(order_id) {
                return Some(order.clone());
            }
        }
        // 查询已撤销订单
        for order in &self.canceled_orders {
            if order.id == Some(order_id) {
                return Some(order.clone());
            }
        }
        None
    }

    pub fn set_subscribe(&mut self, event: Arc<SubscribeEvent>) {
        if event.dtype != events::DataType::OrderDone {
            panic!("ClientRecord 仅支持订单完成事件的订阅");
        }
        self.done_subscribe = Some(event);
    }
}

/// 结算中心结构体
pub struct ClearingCenter {
    // 当前时间戳
    pub current_timestamp_us: AtomicU64,
    // 订单ID生成器
    pub order_id_generator: AtomicU64,
    // 最新成交价格
    pub last_price_cent: RwLock<Option<DashMap<String, u64>>>,
    // 成交历史 (拉取MatchEngine后保存, TODO落库而不是放置在缓存中)
    pub trades: DashMap<String, VecDeque<Trade>>,
    // 用户信息(包括成交历史)
    pub client_records: DashMap<u64, ClientRecord>, // 用户ID -> 账户信息
    // 待校验订单队列（按品种分组）
    pub pending_orders: DashMap<String, VecDeque<Arc<RwLock<Order>>>>, // symbol -> orders
    // 待撤单队列（按订单ID）
    pub pending_cancels: DashSet<u64>, // order_id
    // 手续费率
    pub fee_rate_open: f64,
    pub fee_rate_close: f64,
}

/// 统计信息
#[derive(Debug, Default)]
pub struct SummaryView {
    pub total_trades: u64,
    pub total_trades_value_cents: u64,
    pub total_fees_cents: u64,
    pub total_balance_cents: u64,
    pub balance_fees_cents: u64,
}

/// 结算相关错误
#[derive(Debug)]
pub enum ClearingError {
    UserNotFound,
    SymbolNotFound,
    BalanceNotEnough,
    PositionNotEnough,
    OrderNotFound,
    OrderAlreadyExists,
    Others(String),
}

pub trait ClearingTrait {
    type Error;
    /// 下单
    fn place_order_vertify(&self, order: Order, client_id: u64) -> Result<Order, Self::Error>;
    /// 撤订单
    fn cancel_order_vertify(&self, order_id: u64, client_id: u64) -> Result<(), Self::Error>;
    /// 查询订单
    fn query_order(&self, order_id: u64, client_id: u64) -> Option<Order>;
    /// 放置多空指令以及取消指令给match_engine(经校验后)
    fn place_to_match_engine(&self, match_engine: &(impl MatchEngineTrait + Send + Sync));
    /// 处置上轮成交结果, 更新持仓和账户余额等信息, 同时获悉lastprice
    fn process_trades(&self, match_engine: &(impl MatchEngineTrait + Send + Sync));
}

impl ClearingTrait for ClearingCenter {
    type Error = ClearingError;
    fn place_order_vertify(&self, mut order: Order, client_id: u64) -> Result<Order, Self::Error> {
        // 初始化订单
        self.gen_order_into(&mut order, client_id)?;
        order.timestamp_us = Some(self.current_timestamp_us.load(Ordering::Acquire));

        // 处理市价单 - 转换为最宽裕的限价单
        if order.price.is_none() {
            self.to_market_order(&mut order)?;
        }

        // 将订单先进入待校验队列，后续批量投递到撮合引擎
        let symbol = order.symbol.clone();
        let mut q = self
            .pending_orders
            .entry(symbol)
            .or_insert_with(VecDeque::new);
        let arc_order = Arc::new(RwLock::new(order.clone()));
        // 插入全局待校验队列
        q.push_back(arc_order.clone());
        // 插入账户待处理映射
        self.client_records
            .entry(client_id)
            .or_insert_with(|| ClientRecord::new(client_id))
            .pending_orders
            .insert(order.id.unwrap(), arc_order.clone());
        Ok(order)
    }

    fn cancel_order_vertify(&self, order_id: u64, client_id: u64) -> Result<(), Self::Error> {
        // 获取用户记录
        let mut client_record = self
            .client_records
            .entry(client_id)
            .or_insert_with(|| ClientRecord::new(client_id));
        // 如果还未插入活跃订单则直接取消
        match client_record.pending_orders.remove(&order_id) {
            Some((_, arc_order)) => {
                let mut order = arc_order.write().unwrap();
                order.status = OrderStatus::Canceled;
                client_record.canceled_orders.push_back(order.clone());
                return Ok(());
            }
            None => {}
        }
        // 检验是否在活跃订单
        let is_exist = client_record.active_orders.contains_key(&order_id);
        if !is_exist {
            log::warn!(
                "用户{}的活跃订单中暂时未找到订单ID: {}",
                client_id,
                order_id
            );
            return Err(ClearingError::OrderNotFound);
        }
        // 流程无误则记录撤单请求校验，真正执行在 撮合引擎cancel以及update_orderbooks 中
        self.pending_cancels.insert(order_id);
        Ok(())
    }

    fn query_order(&self, order_id: u64, client_id: u64) -> Option<Order> {
        self.client_records
            .get(&client_id)
            .and_then(|record| record.query_order(order_id))
    }

    fn place_to_match_engine(&self, match_engine: &(impl MatchEngineTrait + Send + Sync)) {
        // 1) 发送撤单请求
        self.pending_cancels.retain(|order_id| {
            let _ = match_engine.cancel_order(*order_id);
            false
        });
        // 2) 将 pending_orders 下发到撮合引擎（通过引擎生成订单ID并进入其 order_queue）
        for mut entry in self.pending_orders.iter_mut() {
            let queue = entry.value_mut();
            while let Some(arc_order) = queue.pop_front() {
                // 简易合法性校验（余额/持仓等复杂逻辑可后续补充）
                let is_valid = {
                    let mut order = arc_order.write().unwrap();
                    self.check_if_valid_order(&mut order)
                };
                match is_valid {
                    true => {
                        let (client_id, order_id) = {
                            let order = arc_order.read().unwrap();
                            (order.client_id, order.id.unwrap())
                        };
                        // 将订单放入撮合引擎，使用订单内的 client_id
                        let _ = match_engine.place_order(arc_order.clone());
                        // 将订单从Pending转入用户活跃订单
                        let client_record = self
                            .client_records
                            .entry(client_id)
                            .or_insert_with(|| ClientRecord::new(client_id));
                        client_record.pending_orders.remove(&order_id);
                        client_record
                            .active_orders
                            .insert(order_id, arc_order.clone());
                    }
                    false => {
                        // 标记拒绝
                        let mut order = arc_order.write().unwrap();
                        if order.status != OrderStatus::Canceled {
                            // 非提前取消订单则拒绝
                            order.status = OrderStatus::Rejected;
                        }
                        self.client_records
                            .get_mut(&order.client_id)
                            .map(|mut rec| rec.canceled_orders.push_back(order.clone()));
                    }
                }
            }
        }
    }

    fn process_trades(&self, match_engine: &(impl MatchEngineTrait + Send + Sync)) {
        // 更新最新成交价
        match self.last_price_cent.write() {
            Ok(mut last_price_opt) => {
                last_price_opt.replace(match_engine.get_last_price_cent().clone());
            }
            Err(e) => {
                log::warn!("Failed to acquire write lock on last_price: {}", e);
            }
        }
        // 获取成交订单和完结订单
        let done_orders = match_engine.done_orders();

        // 通过成交记录改动完结订单的成本(加上交易费率)
        match_engine.trades().par_iter_mut().for_each(|mut entry| {
            let symbol = entry.key().clone();
            let trades = entry.value_mut();
            let mut drained_trades: Vec<Trade> = trades.drain(..).collect();
            drained_trades.par_iter_mut().for_each(|trade| {
                let trade_value = trade.price_cent * trade.quantity;
                // 更新手续费
                trade.fee_long_cent = std::cmp::max(
                    (trade_value as f64 * self.fee_rate_open) as u64,
                    CONFIG.min_fee_cent,
                );
                trade.fee_short_cent = std::cmp::max(
                    (trade_value as f64 * self.fee_rate_close) as u64,
                    CONFIG.min_fee_cent,
                );
                // 更新多方的订单
                let long_value_cent_perstock = (trade_value + trade.fee_long_cent) / trade.quantity;
                done_orders.get(&trade.id_long).map(|order_long| {
                    let mut order = order_long.write().unwrap();
                    order.price = Some(long_value_cent_perstock as f64 / 100.0);
                    // 更新多方余额
                    self.client_records
                        .get_mut(&order.client_id)
                        .map(|mut rec| {
                            rec.balance_cent -= (trade.fee_long_cent + trade_value) as i64;
                        });
                });
                // 更新空方的订单
                let short_value_cent_perstock =
                    (trade_value - trade.fee_short_cent) / trade.quantity;
                done_orders.get(&trade.id_short).map(|order_short| {
                    let mut order = order_short.write().unwrap();
                    order.price = Some(short_value_cent_perstock as f64 / 100.0);
                    // 更新空方余额
                    self.client_records
                        .get_mut(&order.client_id)
                        .map(|mut rec| {
                            rec.balance_cent += (trade_value - trade.fee_short_cent) as i64;
                        });
                });
                // LOG
                tracing::debug!(trade = ?trade, "Processed trade");
            });
            // 转移交易记录至ClearingCenter
            self.trades
                .entry(symbol)
                .or_default()
                .extend(drained_trades);
            // TODO 交易记录落库
        });

        // 将完结订单转移到客户记录中
        done_orders.retain(|&_order_id, arc_order| {
            let order = arc_order.read().unwrap();
            tracing::debug!(
                order = ?order,
                ref_count = Arc::strong_count(arc_order)
            ); // 此处理论上是最后引用
            self.client_records
                .get_mut(&order.client_id)
                .map(|mut rec| rec.insert_done_order(order.clone()));
            false // 转移结束删除该订单在done_orders的位置
        });
    }
}

impl ClearingCenter {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn get_or_create_portfolio(&self, client_id: u64) -> Portfolio {
        let client_record = self
            .client_records
            .entry(client_id)
            .or_insert_with(|| ClientRecord::new(client_id));
        client_record.to_portfolio()
    }

    pub fn client_subscribe_event(&self, client_id: u64, event: Arc<SubscribeEvent>) {
        let mut client_record = self
            .client_records
            .entry(client_id)
            .or_insert_with(|| ClientRecord::new(client_id));
        client_record.set_subscribe(event);
    }

    #[tracing::instrument(skip_all, fields(client_id = order.client_id, order_id = order.id))]
    fn check_if_valid_order(&self, order: &mut Order) -> bool {
        let client_id = order.client_id;
        if client_id == 0 {
            order.frozen_price = Some(0); // Maker无冻结价格
            return true; // Maker默认0, 不做校验
        }
        if order.status != OrderStatus::Unfilled {
            tracing::trace!("提前取消: {:?}", order);
            return false; // 状态非未成交, 说明提前取消了
        }
        let cost_cent_perstock = match order.is_limit {
            true => (order.price.unwrap_or(0.0) * 100.0) as u64,
            false => {
                // 市价单稍微复杂些
                match self.last_price_cent.read() {
                    Ok(last_price_opt) => {
                        let last_price_map = match last_price_opt.as_ref() {
                            Some(map) => map,
                            None => {
                                tracing::warn!("无法获取最新价格，拒绝市价单: {:?}", order);
                                return false;
                            }
                        };
                        let value = match last_price_map.get(&order.symbol).map(|v| *v) {
                            Some(price) => price,
                            None => {
                                tracing::warn!("无法获取最新价格，拒绝市价单: {:?}", order);
                                return false;
                            }
                        };
                        value
                    }
                    Err(_) => {
                        tracing::warn!("无法获取最新价格，拒绝市价单: {:?}", order);
                        return false; // 无法获取价格锁
                    }
                }
            }
        };
        order.frozen_price = Some(cost_cent_perstock); // 记录冻结价格(分)
        let mut portfolio = self
            .client_records
            .entry(client_id)
            .or_insert_with(|| ClientRecord::new(client_id));
        // 检查余额或持仓是否足够
        match order.position_effect {
            PositionEffect::Open => {
                // 开仓检查余额
                let cost_cent = cost_cent_perstock * order.quantity;
                let fee_lock = (cost_cent as f64 * self.fee_rate_open) as i64;
                let amount_least = cost_cent as i64 + fee_lock;
                // 判断余额是否足够
                let is_ok = portfolio.balance_cent >= amount_least
                    && portfolio.balance_available >= amount_least;
                tracing::debug!(
                    "开仓检查: 余额={}, 可用余额={}, 成本={}, 手续费={}, 是否足够={}",
                    portfolio.balance_cent,
                    portfolio.balance_available,
                    cost_cent,
                    fee_lock,
                    is_ok
                );
                // 最低开单总值(仅限限价单)
                if cost_cent < CONFIG.min_order_amount_cent {
                    tracing::warn!(
                        "用户 {} 开单价值太低: {} < {}",
                        client_id,
                        cost_cent,
                        CONFIG.min_order_amount_cent
                    );
                    return false;
                }
                if is_ok {
                    // 冻结余额
                    portfolio.balance_available -= cost_cent as i64; // 锁金额,不锁费用
                } else {
                    tracing::warn!(
                        "用户 {} 可用余额不足: {} < {}",
                        client_id,
                        portfolio.balance_available,
                        amount_least
                    );
                }
                is_ok
            }
            PositionEffect::Close => {
                tracing::info!("平仓检查: 订单={:?}", order);
                let entry_key = (order.symbol.clone(), order.direction);
                let option_position = portfolio.positions_map.get_mut(&entry_key);

                // 平仓检查是否存在满足条件的持仓
                let mut position = match option_position {
                    Some(position) => position,
                    None => {
                        tracing::warn!(
                            "用户 {} 平仓失败: 未找到对应持仓 symbol={}, direction={:?}",
                            client_id,
                            order.symbol,
                            order.direction
                        );
                        return false;
                    }
                };
                let direction_ok = position.side == order.direction;
                let liquidatable_ok = position.liquidatable >= order.quantity;
                let quantity_ok = position.quantity >= order.quantity;
                let is_ok = direction_ok && liquidatable_ok && quantity_ok;
                if is_ok {
                    position.liquidatable -= order.quantity; // 预扣可平仓数量
                } else {
                    tracing::warn!(
                        "用户 {}, 品种{}匹配{} 平仓失败: {}/{} < {}",
                        client_id,
                        position.symbol,
                        direction_ok,
                        position.liquidatable,
                        position.quantity,
                        order.quantity
                    );
                }
                is_ok
            }
        }
    }

    // 统计所有Client-Portfolio以及Trades(包括交易手续费总和, 用于校准测试)
    pub fn summary_all(&self) -> SummaryView {
        let mut summary = SummaryView::default();

        // 统计所有用户的账户余额
        for client_record in self.client_records.iter() {
            let record = client_record.value();
            log::trace!("用户ID: {} 余额: {}", record.client_id, record.balance_cent);
            summary.total_balance_cents += record.balance_cent as u64;
        }

        // 统计所有交易记录
        for trades_entry in self.trades.iter() {
            let trades = trades_entry.value();
            for trade in trades {
                // 累计交易数量
                summary.total_trades += 1;

                // 累计交易价值 (价格 * 数量)
                let trade_value = trade.price_cent * trade.quantity;
                summary.total_trades_value_cents += trade_value;

                // 累计手续费 (买方手续费 + 卖方手续费)
                summary.total_fees_cents += trade.fee_long_cent + trade.fee_short_cent;
            }
        }
        summary.balance_fees_cents = summary.total_balance_cents + summary.total_fees_cents;
        summary
    }

    /// 将市价单处理为BTreeMap的顶底部
    fn to_market_order(&self, order: &mut Order) -> Result<(), ClearingError> {
        let direction = &order.direction;
        let effection = &order.position_effect;
        match (direction, effection) {
            (Direction::Long, PositionEffect::Open) | (Direction::Short, PositionEffect::Close) => {
                // 买单：正无穷
                order.price = Some(i64::MAX as f64 / 100.0);
            }
            (Direction::Short, PositionEffect::Open) | (Direction::Long, PositionEffect::Close) => {
                // 卖单：取0
                order.price = Some(0.0);
            }
        }
        order.is_limit = false;
        Ok(())
    }

    /// 为无id的订单生成唯一ID
    fn gen_order_into(&self, order: &mut Order, client_id: u64) -> Result<u64, ClearingError> {
        // 生成唯一的订单ID和Timestamp
        let time_us_now = self.current_timestamp_us.load(Ordering::Acquire);
        order.id = Some(self.order_id_generator.fetch_add(1, Ordering::SeqCst) * 100);
        order.timestamp_us = Some(time_us_now);
        if order.client_id == 0 {
            //系统默认给0
            order.client_id = client_id;
        }
        if order.client_id != client_id {
            return Err(ClearingError::Others("Client ID mismatch".into()));
        }
        Ok(order.id.unwrap())
    }

    /// 更新当前时间戳(外部传入timestamp)
    pub fn update_timestamp(&self, timestamp_us: u64) {
        self.current_timestamp_us
            .store(timestamp_us, Ordering::Release);
    }
}

impl Default for ClearingCenter {
    fn default() -> Self {
        Self {
            current_timestamp_us: AtomicU64::new(0),
            order_id_generator: AtomicU64::new(1),
            last_price_cent: RwLock::new(None),
            client_records: DashMap::new(),
            trades: DashMap::new(),
            pending_orders: DashMap::new(),
            pending_cancels: DashSet::new(),
            fee_rate_open: CONFIG.fee_rate_open,
            fee_rate_close: CONFIG.fee_rate_close,
        }
    }
}
